﻿<%@ Page Title="分配虚拟仓" Language="C#" MasterPageFile="~/master/m.master" %>

<script runat="server"></script>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <link href="../assets/css/plugins/steps/jquery.steps2.css" rel="stylesheet" />

    <link href="../assets/css/shelf/base.css" rel="stylesheet">
    <link href="../assets/css/distribute/Distribute.css" rel="stylesheet" />
    <link href="../assets/css/plugins/jQuery-DataTables/css/dataTables.bootstrap.min.css" rel="stylesheet" />
    <link href="../assets/css/plugins/iCheck/customsmall.css" rel="stylesheet" />
    <link href="../assets/js/plugins/jQuery-DataTables/extensions/Select/css/select.bootstrap.min.css" rel="stylesheet" />
    <link href="../assets/js/plugins/jQuery-DataTables/extensions/Buttons/css/buttons.bootstrap.min.css" rel="stylesheet" />
    <link href="../assets/css/plugins/select2/select2.min.css" rel="stylesheet" />
    <link href="../assets/css/plugins/select2/select2-bootstrap.min.css" rel="stylesheet" />
    <style>
        /*所有表格行高缩小*/
        .table > tbody > tr > td, .table > tbody > tr > th, .table > tfoot > tr > td, .table > tfoot > tr > th, .table > thead > tr > td, .table > thead > tr > th {
            padding: 2px;
        }
        .bigerswal {
            width: 500px;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="main" runat="Server">
    <div class="system-box">
        <div class="right-side">
            <div class="btns-container">
            </div>
            <div class="condition">
                <form class="form-inline ">
                    <div class="form-group ">
                        <label for="exampleInputName2">通知单号：</label>
                        <input type="text" name="input-billNo" value="" class="form-control input-billNo" size="22" maxlength="30" />
                    </div>
                    <div class="form-group ">
                        <label for="search-materialID-step5">操作员：</label>
                        <select id="search-operator" class="form-control input-w120">
                            <option value="">请选择</option>
                        </select>
                    </div>
                     <div class="form-group ">
                        <label for="exampleInputName2">手工单号：</label>
                        <input type="text" name="input-MaBillNo" value="" class="form-control input-MaBillNo" size="22"  maxlength="80" />
                    </div>
                    
                    单据状态：<b class="cNStateName" spanner>-</b>&nbsp;供应商名称：<b class="vendCustName" spanner>-</b>
                </form>
                <div class="page-tips">
                    <i class="fa fa-lightbulb-o"></i>
                    <span>保存数据同时会生成ERP调拨单据！</span>
                </div>
                <hr class="no-padding no-margins" />
            </div>

            <div class="ibox m-b-xxs">
                <%-- <div class="ibox-title">
                            <span class="text-warning"><i class="fa fa-lightbulb-o">按【<span class="pickTypeNameTxt"></span>】配货，请选择参与本次配货的货号</i></span>
                        </div>--%>
                <div class="ibox-content   " style="overflow: hidden">

                    <div class="row m-n">
                        <div class="col-xs-6 no-padding  " style="padding-right: 14px !important;">
                            <div class="panel panel-default m-b-xxs   m-t-xs overflow-hidde">
                                <table id="tableStep21" class=" table  table-bordered " width="100%" style="margin-top: 0 !important; border: 0; border-bottom: 1px solid #ebebeb;">
                                </table>
                            </div>
                            <div class="no-padding text-center pulltool" style="position: absolute; right: -5px; top: 0;">
                                <a class="pullRight" href="javascript:;"><i class="fa fa-arrow-circle-o-right fa-2x"></i></a>
                                <br />
                                <a class="pullDown" href="javascript:;"><i class="fa fa-arrow-circle-o-down fa-2x"></i></a>
                            </div>
                        </div>
                        <%--                                <div class="col-xs-1  no-padding text-center pulltool">
                                    <a class="pullRight" href="javascript:;"><i class="fa fa-arrow-circle-o-right fa-3x"></i></a>
                                    <br />
                                    <a class="pullDown" href="javascript:;"><i class="fa fa-arrow-circle-o-down fa-3x"></i></a>
                                </div>--%>
                        <div class="col-xs-6  no-padding  " style="padding-left: 14px !important;">
                            <div class="panel panel-default m-b-xxs   m-t-xs overflow-hidde">
                                <table id="tableStep22" class=" table table-bordered " width="100%" style="margin-top: 0 !important; border: 0; border-bottom: 1px solid #ebebeb;">
                                </table>
                            </div>
                        </div>
                    </div>

                </div>

                <%--   <div class="ibox-title m-t-xs" style="border-bottom: 1px solid #f5f5f6;">
                            <b>分配结果</b>
                        </div>--%>

                <div class="ibox-content  contentStep23" style="overflow: hidden">
                    <div class="panel panel-default m-b-xxs   m-t-xs overflow-hidde">
                        <table hidden id="tableStep23" class="table  table-bordered" width="100%" style="margin-top: 0 !important;">
                            <tfoot>
                                <tr>
                                    <th></th>
                                </tr>
                            </tfoot>
                        </table>
                        <div class="text-center h5 p-lg  no-data-23 text-muted" style=""><i class="fa fa-hand-o-right"></i>请选择货号和虚拟仓进行分配</div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="footer" runat="Server">

    <script src="../assets/js/plugins/linq/jquery.linq.min.js"></script>

    <script src="../assets/js/plugins/numeraljs/numeral.min.js"></script>

    <script src="../assets/js/plugins/jQuery-DataTables/jquery.dataTables.min.js"></script>
    <script src="../assets/js/plugins/jQuery-DataTables/dataTables.bootstrap.js"></script>
    <script src="../assets/js/plugins/jQuery-DataTables/extensions/Select/js/dataTables.select.min.js"></script>

    <script src="../assets/js/contabsInIframe.min.js"></script>
    <script src="../assets/js/plugins/iCheck/icheck.min.js"></script>
    <script src="../assets/js/plugins/iCheck/icheckAll.js"></script>
    <script src="../assets/js/plugins/spin/spin.min.js"></script>
    <script src="../assets/js/plugins/select2/select2.full.min.js"></script>
    <script src="../assets/js/plugins/select2/i18n/zh-CN.js"></script>
    <link href="../assets/css/plugins/chosen/chosen.css" rel="stylesheet" />
    <script>

        $(document).ready(function () {
            var ModuleID = Y.getUrlParam("ModuleID");
            var isInsertDCVirtualStock;
            //获取按钮
            commonUtil.loadBtnList(ModuleID, function () {
                $("#btn-save").prop("disabled", "disabled");
                $("#btn-distribution").prop("disabled", "disabled");
            });
            //
            Y.API2('PickingOperations', 'GetOperator', {}, function (data) {
                var newdata = $.map(data, function (obj) {
                    obj.id = obj.UserID;
                    obj.text = obj.UserName;
                    return obj;
                });
                $("#search-operator").select2({
                    language: "zh-CN",
                    theme: "bootstrap",
                    placeholder: "选择操作员",
                    data: newdata
                });
                //选中当前用户
                var UserInfo = JSON.parse(window.sessionStorage.getItem('login-info'));
                if (!Y.checkNull(UserInfo) && !Y.checkNull(UserInfo.NickName)) {
                    // UserInfo.NickName = "xxx";
                    $("#search-operator option:contains('" + UserInfo.NickName + "')").map(function () {
                        if ($(this).text() == UserInfo.NickName) {
                            $(this).prop("selected", true);
                            $("#search-operator").trigger('change');
                        }
                    });

                }
            });

            //通知单号 对应的虚拟仓
            var StockIDList = [];

            var tableStep21, tableStep22, tableStep23;
            var tableStep21Height = 250, tableStep22Height = 250, tableStep23Height = 250;
            var paddingBottom = 5;
            var tableHeadHight = 25, tableHeadMargin = 4;//这个是datatables表头高度 表头
            var tfootHeight = 25; //tfoot 高
            var contentHeight = 0;
            //计算容器大小
            var calcContainer = function () {
                //计算step容器高度

                contentHeight = $('.right-side').height() - $('.condition').outerHeight(true) - 44;//44 是btns-container的高

                $('.ibox').outerHeight(contentHeight, true);
            }
            calcContainer();
            $(window).resize(function () {
                calcContainer();
                resetBox();
            });

            //重置表格高度
            var resetBox = function () {
                var marginTop = 5;//一些框 的外边框
                //平分
                tableStep21Height = tableStep22Height = tableStep23Height = contentHeight / 2;


                $(".pulltool").outerHeight(tableStep21Height);
                $(".ibox-content .panel").outerHeight(tableStep21Height);
                $(".contentStep23").outerHeight(tableStep23Height);
                //console.log(tableStep21Height)
                tableStep21Height -= tableHeadHight;
                tableStep22Height -= tableHeadHight;
                tableStep23Height = tableStep23Height - tableHeadHight - tableHeadMargin - tfootHeight;

                if (tableStep21) {
                    $(tableStep21.table().container()).find(".dataTables_scrollBody").height(tableStep21Height);
                }
                if (tableStep22) {
                    $(tableStep22.table().container()).find(".dataTables_scrollBody").height(tableStep22Height);
                }
                if (tableStep23) {
                    $(tableStep23.table().container()).find(".dataTables_scrollBody").height(tableStep23Height);
                }



            };
            resetBox();

            //数据

            //分配虚拟仓
            var loadTableStep21 = function (data) {
                var opts = {
                    retrieve: true,
                    scrollY: tableStep21Height,
                    language: { url: "../assets/js/plugins/jQuery-DataTables/i18n/Chinese.json" }, scrollX: true, paging: false, info: false, searching: false, ordering: false, lengthChange: false, processing: true,
                    drawCallback: function (setting) {
                        var api = this.api();

                        if (api.rows().data().length > 0) {
                            $(".cNStateName").html(api.rows().data()[0].CNStateName);
                            $(".vendCustName").html(api.rows().data()[0].VendCustName);
                        }

                        tableStep21.$("input.checkItem").iCheck({ checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green", });
                        tableStep21.$("input.checkItem").on("ifChecked", function () {
                            var materialID = tableStep21.$(".checkItem:checked").val();
                            var billNo = $("input[name='input-billNo']").val();

                            //根据货号获取店铺配货需求量数据列表API
                            Y.API2('PickingOperations', 'GetDCVirtualStock', { BillNo: billNo, MaterialID: materialID }, function (data) {
                                tableStep22.$("input.checkItem").iCheck('uncheck');
                                //权限禁用
                                if (data.IsAllot) {
                                    $("#btn-save").prop("disabled", true);
                                    $("#btn-distribution").prop("disabled", true);
                                } else {
                                    $("#btn-save").prop("disabled", false);
                                    $("#btn-distribution").prop("disabled", false);
                                }
                                if (data.List.length > 0) {

                                    if (tableStep23) {
                                        clearTable23();
                                    }
                                    loadTableStep23(1, data.List);
                                    var arr = $.Enumerable.From(data.List).GroupBy("{StockID:$.StockID, StockName:$.StockName}", null, "$", function (x) {
                                        var _arr = [];
                                        for (var i in x) {
                                            _arr.push(x[i]);
                                        }

                                        return _arr.join("-");
                                    }).ForEach(function (x) {
                                        //选中虚拟仓
                                        tableStep22.$("input.checkItem").filter("[value='" + x.StockID + "']").iCheck('check');
                                    });

                                    //已经分配过可以下一步
                                    isInsertDCVirtualStock = true;
                                }
                                else {
                                    $.each(StockIDList, function (i, obj) {
                                        //选中默认虚拟仓
                                        tableStep22.$("input.checkItem").filter("[value='" + obj.StockID + "']").iCheck('check');
                                    });
                                    if (tableStep23) {
                                        clearTable23();
                                        loadTableStep23(1);
                                    }
                                }

                            });
                        });
                        //高度

                        //$(tableStep21.table().node()).height("100%");
                        //$(tableStep21.table().node()).height($(tableStep21.table().node()).height() - 3);//多一像素 下边框

                        //   isInsertDCVirtualStock

                    },
                    createdRow: function (row, data, dataIndex) {
                        if ($(row).find("td:first[data-groupstart]").length > 0) {//给分组加粗线
                            $(row).addClass("groupRow");
                        }
                    },
                    columnDefs: [
                         {//==============================================分组分组分组分组分组分组分组分组分组分组分组=================================================================================
                             "targets": [1, 2],//要合并的字段
                             "searchable": false,
                             createdCell: function (td, cellData, rowData, row, col) {

                                 var gcol = [{ colName: 2, group: 1, baseGroup: 0 }];//要合并的组的条件，colName为对应的字段index，group：分组（1，2，3...） baseGroup:（父id）必须存在targets 中
                                 $(tableStep21.cell(row, col).nodes()).addClass("groupbyColumn-" + row + " groupbyColumn-" + row + "-" + col);

                                 var condition = false;
                                 if (row != 0) {
                                     var g = $.Enumerable.From(gcol).GroupBy("$.group", "", function (key, e) {
                                         //   //console.log(key)
                                         return { group: key, info: e.Select('{"colName":$.colName,"baseGroup":$.baseGroup}').ToArray() };
                                     }, "$.toString()");

                                     //判断是否作为条件
                                     var isGroup = g.Count(function (arr) {
                                         var b = false;
                                         $.each(arr.info, function (i, obj) {
                                             if (obj.colName == col) {
                                                 b = true;
                                             }
                                         });
                                         return b;
                                     }) > 0;
                                     // //console.log(col + ":" + isGroup);
                                     g.ForEach(function (arr) {
                                         var e = $.Enumerable.From(arr.info);
                                         if (e.Count(function (info) { return info.colName == col }) > 0) {
                                             e.ForEach(function (obj) {
                                                 if (tableStep21.cell(row, obj.colName).data() != tableStep21.cell(row - 1, obj.colName).data()) {
                                                     //遍历所有条件
                                                     condition = true;
                                                 }
                                                 if (obj.baseGroup != 0) {//是否根级
                                                     nextGroup(obj)
                                                 }
                                             });
                                         }
                                         if (!isGroup) {//不参数与条件筛选的也要和第一组一样
                                             e.ForEach(function (obj) {
                                                 if (obj.baseGroup == 0) {
                                                     if (tableStep21.cell(row, obj.colName).data() != tableStep21.cell(row - 1, obj.colName).data()) {
                                                         condition = true;
                                                     }
                                                 }

                                             });
                                         }
                                     });
                                     function nextGroup(obj) {//迭代下级
                                         g.Where(function (arr) {//查找上级
                                             return arr.group == obj.baseGroup;
                                         }).ForEach(function (arr2) {
                                             var e2 = $.Enumerable.From(arr2.info);
                                             e2.ForEach(function (obj2) {
                                                 if (tableStep21.cell(row, obj2.colName).data() != tableStep21.cell(row - 1, obj2.colName).data()) {
                                                     condition = true;
                                                 }
                                                 nextGroup(obj2);
                                             });
                                         });

                                     }

                                 }

                                 var start = 0;
                                 for (var i = row; i >= 0; i--) {
                                     var _starcol = $(tableStep21.cell(i, col).node()).attr("data-groupStart");
                                     if (_starcol > 0) {
                                         start = _starcol;
                                         break;
                                     }
                                 }
                                 //   var start =
                                 if (condition) {
                                     ////console.log("row - groupIndex - 1")
                                     ////console.log(row - groupIndex - 1)
                                     $(td).attr("data-groupStart", row);// $("td:[data-groupStart]").attr("data-groupStart").attr();
                                     $(tableStep21.cell(start, col).node()).prop("rowspan", row - start);
                                     //  groupIndex = 0;//组index重新开始
                                 } else {
                                     if (row == 0)//给第一行标记
                                     {
                                         $(td).attr("data-groupStart", row);
                                     } else {
                                         $(td).addClass("hide");
                                     }
                                     if (tableStep21.data().length - 1 == row)//最后一行
                                     {
                                         $(tableStep21.cell(start, col).node()).prop("rowspan", tableStep21.data().length - start);
                                     }
                                 }

                                 if (tableStep21.cell(row - 1, col).data() == cellData) {
                                     //   $(td).prop("rowspan", 2);
                                 }

                             }
                             // ===============================================end分组分组分组分组分组分组分组分组分组分组分组end===============================================================================
                         },
                    ],
                    columns: [
                         { name: "SourceBillNo", title: "SourceBillNo", data: "SourceBillNo", visible: false },
                     {
                         data: null, Sortable: false, targets: 0,
                         title: "", className: "text-center",
                         render: function (data, type, row, meta) {
                             return '<input type="radio" name="checkItemstep21" class="checkItem" value="' + row.MaterialID + '" />';
                         },
                     },
                    { name: "MaterialID", title: "货号", data: "MaterialID", className: "text-center", defaultContent: "" },
                    { title: "尺码", "data": "SizeName", className: "text-center", defaultContent: "" },
                    { title: "单据数量", "data": "TotalQty", className: "text-center", defaultContent: "" }
                    ]
                };

                if (data == 1) {
                    opts.ajax = function (data, callback, settings) {
                        callback(
                        { "data": [] });
                    };
                } else {
                    var _url = "/api.ashx?c=PickingOperations&a=GetPMArrNoticeList";
                    opts.ajax = {
                        url: _url,
                        type: "POST",
                        dataSrc: function (json) {
                            if (json.Success == false) {
                                swal(json.Message, '', 'error');
                                return [];
                            } else {

                                if (json.Data.List.length == 0) {
                                    $(".cNStateName").html("-");
                                    $(".vendCustName").html("-");
                                }
                                StockIDList = json.Data.StockIDList;


                                return json.Data.List;
                            }
                        },
                        data: data
                    };
                }
                tableStep21 = $('#tableStep21').DataTable(opts);

            }
            var loadTableStep22 = function () {
                tableStep22 = $('#tableStep22').DataTable({
                    ajax: {
                        url: "/api.ashx?c=OdsErpBasArea&a=GetAllOdsErpBasStockList",
                        type: "POST",
                        dataSrc: function (json) {
                            //  if(json.Data.length / 2)
                            if (json.Success == false) {
                                swal(json.Message, '', 'error');
                                return [];
                            } else {
                                // json.data = json.Data;
                                //把广东仓的删除 特殊处理
                                $.Enumerable.From(json.Data).ForEach(function (x, i) {
                                    if (x.StockName == '广东仓')
                                    {
                                      json.Data.splice(i,1);
                                    }
                                    
                                });
                                var m = json.Data.length % 3 == 0;
                                var _leng = m ? json.Data.length : parseInt(json.Data.length / 3) + 1;
                                json.data = [];
                                var skip = -1;
                                //console.log(json.Data)
                                $.map(json.Data, function (obj, i) {
                                    if ((i + 1) % 3 == 1) {
                                        skip++;
                                        json.data.push({
                                            StockCode: json.Data[i].StockCode, StockID: json.Data[i].StockID, StockName: json.Data[i].StockName
                                            , StockCode2: "", StockID2: "", StockName2: "",
                                            StockCode3: "", StockID3: "", StockName3: ""
                                        })

                                    }
                                    //console.log(skip)
                                    //console.log(json.data)
                                    if ((i + 1) % 3 == 2) {

                                        json.data[skip]["StockCode2"] = json.Data[i].StockCode;
                                        json.data[skip]["StockID2"] = json.Data[i].StockID;
                                        json.data[skip]["StockName2"] = json.Data[i].StockName;
                                    }
                                    if ((i + 1) % 3 == 0) {
                                        json.data[skip]["StockCode3"] = json.Data[i].StockCode;
                                        json.data[skip]["StockID3"] = json.Data[i].StockID;
                                        json.data[skip]["StockName3"] = json.Data[i].StockName;
                                    }

                                    //if (_leng > i) {
                                    //    if (_leng + i <= json.Data.length - _leng - 1) {
                                    //        obj.StockCode2 = json.Data[_leng + i].StockCode;
                                    //        obj.StockID2 = json.Data[_leng + i].StockID;
                                    //        obj.StockName2 = json.Data[_leng + i].StockName;
                                    //    }else if (_leng + i <= json.Data.length - 1) {
                                    //        obj.StockCode3 = json.Data[_leng + i].StockCode;
                                    //        obj.StockID3 = json.Data[_leng + i].StockID;
                                    //        obj.StockName3 = json.Data[_leng + i].StockName;
                                    //    } else {
                                    //        obj.StockCode2 = "";
                                    //        obj.StockID2 = "";
                                    //        obj.StockName2 = "";
                                    //    }
                                    //}

                                });
                                json.data.splice(_leng, json.Data.length);
                                //console.log(json)
                                return json.data;
                            }
                        }
                    },
                    scrollY: tableStep22Height,
                    scrollCollapse: true,
                    retrieve: true,
                    language: { url: "../assets/js/plugins/jQuery-DataTables/i18n/Chinese.json" }, scrollX: true, searching: false, paging: false, info: false, ordering: false, lengthChange: false, processing: true,
                    drawCallback: function (setting) {
                        var api = this.api();
                        $(tableStep22.table().container()).find(".checkItem").iCheck({ checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green", });
                        tableStep22.$("input.checkItem").off("ifClicked");
                        tableStep22.$("input.checkItem").on("ifClicked", function () {

                            if (tableStep21.$("input.checkItem:checked").length == 0) {
                                swal("请选择货号");
                            }
                        });
                        //    $(tableStep21.table().container()).icheckAll({
                        //        checkObj: ".checkItem",//表格下面的选择控件对象 选择器
                        //        checkAllObj: "#checkAll",//全选 选择器
                        //        clickoutBoxCheck: false //点击行 不选中
                        //});
                    },
                    
                    columns: [
                     {
                         data: "StockID", Sortable: false, targets: 0,
                         title: "", className: "text-center",
                         render: function (data, type, row, meta) {
                             return '<input type="checkbox" name="checkItemstep22" class="checkItem" data-text="' + row.StockName + '" value="' + row.StockID + '" />';
                         },
                     },
                    { title: "虚拟仓", data: "StockName", className: "text-center", width: "27%" },
                     {
                         data: "StockID2", Sortable: false, targets: 0,
                         title: "", className: "text-center",
                         render: function (data, type, row, meta) {
                             if (Y.checkNull(row.StockID2))
                                 return "";
                             else
                                 return '<input type="checkbox" name="checkItem" class="checkItem" data-text="' + row.StockName2 + '"  value="' + row.StockID2 + '" />';
                         },
                     },
                    { title: "虚拟仓", data: "StockName2", className: "text-center", width: "27%" },
                    {
                        data: "StockID3", Sortable: false, targets: 0,
                        title: "", className: "text-center",
                        render: function (data, type, row, meta) {
                            if (Y.checkNull(row.StockID3))
                                return "";
                            else
                                return '<input type="checkbox" name="checkItemstep22" class="checkItem" data-text="' + row.StockName3 + '" value="' + row.StockID3 + '" />';
                        },
                    },
                    { title: "虚拟仓", data: "StockName3", className: "text-center", width: "27%" },

                    ]
                });
            }
            var loadTableStep23 = function (state, tabledata) {
                $("#tableStep23").show();
                isInsertDCVirtualStock = false;
                var opts = {

                    scrollY: tableStep23Height,//25是tfoot高
                    language: { url: "../assets/js/plugins/jQuery-DataTables/i18n/Chinese.json" }, scrollX: true, searching: false, paging: false, info: false, ordering: false, lengthChange: false, processing: true,
                    footerCallback: function (tfoot, data, start, end, display) {
                        //console.log("footerCallback")
                        var api = this.api(), data;
                        if (data.length > 0) {

                            var sizeCount = data[0].SizeCount;
                            var footTr = '<th colspan="2" class="text-center">可配数量</th><th hidden class="text-center"> </th>';
                            for (var i = 0; i <= sizeCount - 1; i++) {
                                footTr += '<th class="text-center"></th>';
                            }

                            $(tfoot).html(footTr);
                            calcAssignResult();
                        }
                    },

                    drawCallback: function () {
                        // tableStep23.cell(0,0).data(55).draw();
                        //console.log("drawCallback")
                        var keyChange = false;
                        //分配结果事件
                        tableStep23.$("input[name='step23InlineInput']").off("change");
                        tableStep23.$("input[name='step23InlineInput']").on("change", function () {
                            var e = e || event;
                            //  //console.log(e.type)

                            var v = $(this).val();
                            var td = $(this).parent("td");
                            var r = /^[0-9]*[0-9][0-9]*$/
                            if (!r.test(v)) {
                                swal("请输入正整数！");
                                tableStep23.draw();
                                return;
                            }
                            //  if (keyChange) { clearTimeout(keyChange); }
                            //  keyChange = setTimeout(function () {
                            tableStep23.cell(td).data(parseInt(v));
                            tableStep23.draw();
                            //  }, 1000);
                        });
                        $(".no-data-23").hide();

                    }
                };
                if (state != 1) {
                } else {
                    if (Y.checkNull(tabledata)) {
                        opts.ajax = function (data, callback, settings) {
                            //console.log("ajax")
                            callback(
                { "data": [] });
                        };

                    } else {

                        createData(tabledata);
                    }
                }
                //console.log(tabledata);
                function createData(json) {
                    var tempList = { data: [] };
                   // console.log(2343);
                   // console.log(json);
                    //var json2 = [{ StockID: "KM000083", StockName: "广东仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "M1", SizeName: "M", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" },
                    // { StockID: "KM000083", StockName: "广东仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "1L", SizeName: "L", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" },
                    // { StockID: "KM000083", StockName: "广东仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "XL1", SizeName: "XL", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" },
                    // { StockID: "KM001121", StockName: "京北仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "M1", SizeName: "M", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" },
                    // { StockID: "KM001121", StockName: "京北仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "L1", SizeName: "L", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" },
                    // { StockID: "KM001121", StockName: "京北仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "X1L", SizeName: "XL", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" },
                    // { StockID: "KM000876", StockName: "湖南仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "M1", SizeName: "M", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" },
                    // { StockID: "KM000876", StockName: "湖南仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "L1", SizeName: "L", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" },
                    // { StockID: "KM000876", StockName: "湖南仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "XL1", SizeName: "XL", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" }
                    //{ StockID: "KM000876", StockName: "湖南仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "XXL", SizeName: "XXL", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" },
                    //{ StockID: "KM000876", StockName: "湖南仓", SourceBillNo: "AN170313KMHK5171-001", SizeID: "XXXL", SizeName: "XXXL", TotalQty: 300, CompanyID: "KM", MaterialID: "1J1112002L0" },
                    // ];
                    //数据重组
                    opts.columns = [
                         { data: "StockName", Sortable: false, title: "虚拟仓", className: "text-center", width:100 },
                        { data: "MaterialID", Sortable: false, title: "货号", className: "text-center", width: 110 },
                    ];
                    //console.log("API3")
                    var _i = 0
                    var g = $.Enumerable.From(json).GroupBy("{CompanyID:$.CompanyID, StockID:$.StockID, SourceBillNo:$.SourceBillNo, StockName:$.StockName, MaterialID:$.MaterialID}", null,
                           function (key, e) {

                               var _templist = key;

                               e.ForEach(function (x) {
                                   _templist[x.SizeName] = x.TotalQty;
                                   _templist["SizeID" + x.SizeName] = x.SizeID;
                                   if (_i == 0)
                                       opts.columns.push({
                                           data: x.SizeName, Sortable: false, title: x.SizeName, className: "text-center",
                                           render: function (data, type, row, meta) {
                                               //console.log("render")
                                               // //console.log(row[x.SizeName])
                                               return '<input type="number" name="step23InlineInput"  class="form-control input-sm inlineInput p-xxs" style="width:100%" data-size="' + x.SizeName + '" value="' + row[x.SizeName] + '" />';
                                           }
                                       });

                               });
                               _templist["SizeCount"] = e.Count();//尺码数
                               _i++;
                               tempList.data.push(_templist);
                               return key;
                           }, function (x) {
                               var _arr = [];
                               for (var i in x) {
                                   _arr.push(x[i]);
                               }
                               return _arr.join("-");
                           }).ToArray();
                   // console.log("Enumerable")
                 //   console.log(tempList)
                    opts.ajax = function (data, callback, settings) {
                        //console.log("ajax")
                        callback(tempList);
                    };
                }
                //要先清空表头，因为动态列不同时会出错
                if (tableStep23 && !Y.checkNull(tabledata)) {
                    $(tableStep23.table().header()).find("tr").html("");
                }
                tableStep23 = $('#tableStep23').DataTable(opts);
            }
            var clearTable23 = function () {
                $(tableStep23.table().footer()).find("tr th").remove();//特殊处理，由于datatables没有动态处理tfoot功能
                tableStep23.clear();
                tableStep23.destroy();

            }



            if (tableStep21) tableStep21.destroy()
            loadTableStep21(1);
            if (tableStep22) tableStep22.destroy()
            loadTableStep22();
            if (tableStep23) {
                clearTable23();

                loadTableStep23(1);
            }
            //保存 分配虚拟仓
            $(document).on("click", "#btn-save", function () {
                if (!tableStep23 || tableStep23.data().length == 0) {
                    swal("请分配虚拟仓！", '', 'warning');
                    return;
                }
                if ($(tableStep23.footer()).find(".text-danger").length > 0)//不能保存
                {
                    swal("分配数量不对！", '', 'warning');
                    return;
                }
                var operatorID = $("#search-operator").val();
                if (Y.checkNull(operatorID))//不能保存
                {
                    swal("操作员不能为空！", '', 'warning');
                    return;
                }
                var maBillNo = $("input[name='input-MaBillNo']").val();

                swal({ title: "确定要保存吗?", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "确 定", closeOnConfirm: false, cancelButtonText: "取 消", }, function () {
                    var insertDCVirtualStockModel = [];
                    //数据集转换  列转行
                    if (tableStep23.data()) {
                        tableStep23.data().each(function (row, i) {
                            // console.log(tableStep23.row(i).data());
                            tableStep23.columns().data().each(function (col, j) {

                                if ($.isNumeric(tableStep23.cell(0, j).data()))//判断是否数字 排除 虚拟仓和货号，留下尺码
                                {

                                    var _tempRow = {};


                                    _tempRow.CompanyID = row.CompanyID;
                                    _tempRow.SourceBillNo = tableStep21.data()[0].SourceBillNo;
                                    _tempRow.StockID = row.StockID;
                                    _tempRow.MaterialID = row.MaterialID;
                                    _tempRow.SizeID = tableStep23.row(i).data()["SizeID" + tableStep23.column(j).dataSrc()];
                                    _tempRow.TotalQty = tableStep23.cell(i, j).data();
                                    insertDCVirtualStockModel.push(_tempRow);
                                }
                            });
                        });
                        layer.closeAll('dialog');
                        layer.msg('正在保存……', { icon: 16, shade: 0.01, time: 0, maxWidth: 200 });
                        Y.API2('PickingOperations', 'InsertDCVirtualStock', {
                            UserID: operatorID,
                            list: insertDCVirtualStockModel,
                            MaBillNo: maBillNo
                        }, function (data) {
                            layer.closeAll('dialog');
                           
                           if (data.Success == false) {
                                swal(data.Message, '', 'error');
                            }
                            else {


                                
                                //已经分配可以下一步
                                isInsertDCVirtualStock = true;
                                //swal('保存成功', '', 'success');
                                var _list = "";
                                switch (data.RetVal) {
                                    case -1:
                                    case 1:
                                    case 2:
                                    case 3:
                                        debugger;
                                        swal({ title: "<span style='font-size:16px'>" + data.Message + "</span>", type: "error", html: true });

                                        break;
                                    case 0:
                                        //保存成功后禁用按钮
                                        $("#btn-save").prop("disabled", true);
                                        $("#btn-distribution").prop("disabled", true);
                                        if (data.List.length<=5){//如果只有5个以内用列表
                                        $.each(data.List, function (i, obj) {
                                            _list += '<li class="list-group-item">' + obj.BillNo + '</li>';
                                        });
                                        swal({ title: "<span style='font-size:16px'>" + data.Message + "，单号如下:</span>", text: '<ul class="list-group">' + _list + '</ul>', type: "success", html: true, customClass: "bigerswal" });
                                        }else{
                                        _list += '<thead><tr><th class="text-center">单号<th class="text-center">单号</th></tr></thead>';
                                        _list += "<tbody>";
                                        $.each(data.List, function (i, obj) {
                                            if ((i + 1) % 2 == 0) return true;
                                            _list += '<tr><td>' + data.List[i].BillNo + '</td><td>' + (Y.checkNull(data.List[i + 1]) ? "" : data.List[i + 1].BillNo) + '</td></tr>';
                                        });
                                        _list += "</tbody>";
                                        // console.log(_list)
                                        swal({ title: "<span style='font-size:16px'>" + data.Message + "，单号如下:</span>", text: '<table id="ErpRS" width="100%" class="table table-bordered table-responsive text-center">' + _list + '</table>', type: "success", html: true, customClass: "bigerswal" });
                                        }
                                        break;
                                }
                                var opts = {
                                    pageLength: 10,
                                    language: { url: "../assets/js/plugins/jQuery-DataTables/i18n/Chinese.json" }, scrollX: true, searching: false, ordering: false, lengthChange: false,
                                    drawCallback: function () {
                                        $(".bigerswal").css("margin-top", (-$(".bigerswal").outerHeight() / 2) + "px");
                                    }
                                };

                                $('#ErpRS').dataTable(opts);


                            }
                        });

                    }

                });



            });
            //分配 分配虚拟仓
            $(document).on("click", "#btn-distribution", function () {
                var materialID = tableStep21.$(".checkItem:checked").val();
                // materialID = "1152C5210250101";//测试的

                var stock = [];
                tableStep22.$(".checkItem:checked").each(function () {
                    stock.push({ StockID: $(this).val(), StockName: $(this).attr("data-text") });
                });
                //  console.log(stock)

                if (Y.checkNull(stock)) {
                    swal("请选择虚拟仓！");
                    return;
                }
                if (Y.checkNull(materialID)) {
                    swal("请选择货号！");
                    return;
                }

                //var array1 = [13,413,5];
                //var array2 = [13,14,53,6];

                //var aa= $.Enumerable.From(array1)
                // .Join(array2, function (x) { console.log("1"); console.log(x); return x + 1; }, function (x) { console.log("2"); console.log(x); return x; }, function (inner,outer) {

                //     return {inner:inner,outer:outer};
                // });
                // var aa= $.Enumerable.From(array1)
                //.Concat(array2);
                // console.log(aa.ToArray());
                //  return false;

                Y.API2('PickingOperations', 'GetFirstAllotList', { StockID: $.Enumerable.From(stock).Select("$.StockID").ToString(","), MaterialID: materialID }, function (data) {
                    var tmep = [];
                    var dataNew = $.Enumerable.From(tableStep21.data()).Where(function (x) { return x.MaterialID == materialID; }).Join(stock, "", "", function (inner, outer) {
                        outer.TotalQty = 0;
                       
                        var n = $.extend({}, inner, outer);
                        
                        return n;
                    }, function () { return true; }).ToArray();
                
                    var dataNew
                    if (data.length > 0) {
                        if (tableStep23) {
                            clearTable23();
                        } 
                        $.each(data, function (i, obj) {
                            $.Enumerable.From(dataNew).Where(function (x) { return x.CompanyID == obj.CompanyID && x.MaterialID == obj.MaterialID && x.SizeID == obj.SizeID && x.StockID == obj.StockID }).ForEach(function (x) {
                                x.TotalQty = obj.TotalQty;
                                //合并
                               // $.extend( x, obj);
                                
                            });
                        });
                      //  console.log(dataNew)
                        loadTableStep23(1, dataNew);


                    }
                    else {

                        //  { CompanyID: "KM", SourceBillNo: tmep.SourceBillNo, StockID: "", StockName: "", MaterialID: materialID, SizeID: "M1", SizeName: "M", TotalQty: tmep.TotalQty }
                        //   ];
                        // $("stockID")

                        //console.log(dataNew)

                        if (tableStep23) {
                            clearTable23();

                        }
                        loadTableStep23(1, dataNew);
                    }

                });

            });
            //查询 分配虚拟仓
            $(document).on("click", "#btn-search", function () {
                if (tableStep23) {
                    clearTable23();

                    loadTableStep23(1);
                }
                if (tableStep22) {
                    tableStep22.$("input.checkItem").iCheck("uncheck");
                }

                var billNo = $("input[name='input-billNo']").val();
                if (Y.checkNull(billNo)) {
                    swal("通知单号不能为空！");
                    return;
                }


                if (tableStep21) tableStep21.destroy();
                var spinner = new Spinner({ scale: 0.4 }).spin();
                $(".billNo[spanner],.cNStateName[spanner],.vendCustName[spanner]").html(spinner.el);
                loadTableStep21({ BillNo: billNo });

            });



            //计算 分配结果
            var calcAssignResult = function () {

                if (tableStep23.data()) {
                    var _material = tableStep21.data().filter(function (obj, ii) {
                        return obj.MaterialID == tableStep23.row(0).data().MaterialID; //找对应货号
                    });
                    for (var i = tableStep23.columns().data().length - 1; i >= 0; i--)//循环列
                    {

                        if ($.isNumeric(tableStep23.cell(0, i).data()))//判断是否数字 排除列 虚拟仓和货号，留下尺码
                        {
                            var qty = 0;
                            _material.filter(function (obj, ii) {
                                return obj.SizeName == tableStep23.column(i).dataSrc();
                            }).each(function (o) {//其实原理上到这里只有一条数据
                                //console.log(o);
                                qty = o.TotalQty;
                            });
                            var sum = tableStep23.column(i).data().reduce(function (a, b) {
                                return a + b;
                            });
                            //console.log(tableStep23.column(i).footer())
                            var r = qty - sum;
                            var fth = $(tableStep23.table().footer()).find("tr th").eq(i);
                            fth.html(r);
                            if (r != 0) {
                                fth.addClass("text-danger");
                            } else {
                                fth.removeClass("text-danger");
                            }
                        }

                    }
                }

            }
        });
    </script>
</asp:Content>

